<template>
  <v-container>
    <v-row>
      <v-col cols="2">
        <v-card id="category">
          <v-list dense>
            <v-subheader>分类</v-subheader>
            <v-list-item-group v-model="category" mandatory color="primary">
              <v-list-item @click="queryNewIndex()">
                <v-list-item-content>
                  <v-list-item-title>最新</v-list-item-title>
                </v-list-item-content>
              </v-list-item>
              <v-list-item @click="queryNewFollowsIndex()" v-show="this.user.userId">
                <v-list-item-content>
                  <v-list-item-title>我的关注</v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-card>
      </v-col>

      <v-col offset="1" cols="6" >
        <!-- 发布区 -->
        <v-form class="white px-5 py-2 mb-5" ref="form">
          <v-textarea
            hint="内容请控制在1-255字以内"
            outlined
            counter="255"
            rows="3"
            placeholder="有什么新鲜事想分享呢？"
            :rules="feedRules"
            v-model="sendContent"
            @blur="blurFeed()"
          ></v-textarea>

          
          <div class="d-flex justify-space-between">

            <v-checkbox
              v-model="status"
              dense
              label="匿名"
              class="mt-0"
            ></v-checkbox>
            <v-btn depressed dark color="teal" @click="sendFeed()">发布</v-btn>
          </div>
        </v-form>

        <!-- 动态区 -->
        <my-feed :feed="message"
          @queryFeed="queryIndexFeed()" 
          v-for="message in messages" 
          :key="message.forwardId +'#'+ message.feedId">
        </my-feed>
        <el-empty v-show="messages.length == 0" description="暂无动态"></el-empty>
        <el-empty v-show="messages.length != 0 && this.noMore" description="已经没有内容了"></el-empty>
      </v-col>
    </v-row>

    <v-btn
      fab
      dark
      large
      color="cyan"
      id="back_top"
      v-show="showBtn"
      @click="backTop()"
    >
      <v-icon dark>mdi-chevron-up</v-icon>
    </v-btn>
  </v-container>
</template>

<script>
import MyFeed from '../views/MyFeed.vue'

export default {
  name: 'MyIndex',
  components: {MyFeed},
  data: ()=>({
    isAchiveBottom: true,
    noMore: false,
    showBtn: false,
    pageSize: 5,
    pageNum: 1,
    messages: [],
    category: 0,
    feedRules:[
      v => !!v || '评论不能为空！',
      v => (v && v.length > 0 && v.length <= 255) || '评论内容请控制在1-255字以内！'
    ],
    sendContent: '',
    status: false,
    key: 0
  }),
  created(){
    // 绑定鼠标滚轮事件，动态分页查
    window.onscroll = () => {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

      // 如果进度条到达1/3，那么出现回到顶部按钮
      if(scrollTop > scrollHeight / 3){
        this.showBtn = true
      }else{
        this.showBtn = false
      }

      if (
        scrollTop + windowHeight >= scrollHeight - 20 &&
        !this.isAchiveBottom &&
        !this.noMore
      ){
        // 防止重复发送分页
        this.isAchiveBottom = true;

        setTimeout(() => {
          // 如果查到的结果为空，那么把noMore设置为true，并显示已无内容
          this.pageNum++;

          if(this.category == 0) this.queryIndex()
          else this.queryFollowsIndex()
        }, 500);
      }
    }

    this.queryIndex()
  },
  computed: {
    user(){
      return this.$store.state.user
    },
  },
  methods:{
    // 回到顶部
    backTop(){
      document.documentElement.scrollIntoView({behavior: "smooth"})
    },
    // 按照时间逆序得到所有的转发+动态
    doQueryIndex(url, config){
      this.$utils.doGetAxios(this, url, config, (data)=>{
        data.list.forEach((item)=>{
          if(item.forwardId){
            item.forwardTime = this.$utils.dateFormat(item.forwardTime)
            item.time = this.$moment(item.time).format("YYYY-MM-DD HH:mm:ss")
          }else{
            item.time = this.$utils.dateFormat(item.time)
          }
          this.messages.push(Object.assign({}, item, { showComment: false, sendContent: '', comments: [] }))
        })

        if(data.isLastPage){
          // 没有内容了
          this.noMore = true
        }else{
          this.isAchiveBottom = false;
        }
      })
    },
    queryIndex(){
      const userId = this.user.userId
      const token = this.user.token
      const pageSize = this.pageSize
      const pageNum = this.pageNum

      if(userId && token){
        this.doQueryIndex('/api/feed/u',  {
          params:{userId, pageSize, pageNum},
          headers: {token }
        })
      }else{
        this.doQueryIndex('/api/feed', {
          params:{pageSize, pageNum},
        })
      }
    },
    // 查询用户关注！
    queryFollowsIndex(){
      const userId = this.user.userId
      const token = this.user.token
      const pageSize = this.pageSize
      const pageNum = this.pageNum
      if(userId && token){
        this.doQueryIndex('/api/feed/follows',  {
          params:{userId, pageSize, pageNum},
          headers: {token }
        })
      }
    },
    // 查最新
    queryNewIndex(){
      Object.assign(this.$data, this.$options.data())
      this.queryIndex()
    },
    // 查最新用户关注
    queryNewFollowsIndex(){
      Object.assign(this.$data, this.$options.data())
      this.queryFollowsIndex()
    },
    // 刷新当前页数据
    queryIndexFeed(){
      const category = this.category
      Object.assign(this.$data, this.$options.data())
      this.category = category
      if(category == 0) this.queryIndex()
      else this.queryFollowsIndex()
    },
    // 当要发送的feed失去焦点
    blurFeed(){
      this.$refs.form.resetValidation()
    },
    doSendFeed(url, data, config){
      this.$utils.doPostAxios(this, url, data, config, (data, msg)=>{
        this.$message.success(msg)
        // 刷新页面
        this.blurFeed()
        this.queryIndexFeed()
      })
    },
    // 发送一条feed
    sendFeed(){
      if(!this.$refs.form.validate()){
        return
      }

      const token = this.user.token
      const userId = this.user.userId
      const content = this.sendContent
      const status = this.status?0:1

      if(token && userId){
        this.$messageBox.confirm('确认发布动态？', '动态', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 发送转发请求
          this.doSendFeed('/api/feed', 
            this.$qs.stringify({userId, content, status}), {
              headers: {token }
           }, token)
        }).catch(()=>{})
      }else{
        this.$message.warning("请用户先登录！")
      }
    }
  }
}
</script>

<style scoped>
#category{
  position: fixed;
  width: 200px;
}
#back_top{
  position: fixed;
  right: 20px;
  bottom: 20px;
}
</style>